package yagwl.service.demo;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

import yagwl.service.util.svc.CacheService;
import yagwl.service.util.svc.Context;
import yagwl.service.util.svc.ServiceInvocationHandler;
import yagwl.service.util.svc.CacheService.CacheLoaderCallback;

public class LaureateServiceImpl implements LaureateService {

  private static CacheService cacheSvc;
  private static CountryCacheLoaderCallback countryCallback;
  private static final LaureateServiceImpl svc = new LaureateServiceImpl();

  private LaureateServiceImpl() {
    if (cacheSvc != null)
      return;
    cacheSvc = CacheService.getInstance();
    countryCallback = this.new CountryCacheLoaderCallback();
    cacheSvc.registerCacheLoaderCallback("LaureateCountry", countryCallback);
  }

  public static LaureateService getInstance() {
    InvocationHandler handler = new ServiceInvocationHandler(svc);
    LaureateService proxy = (LaureateService) Proxy.newProxyInstance(svc
        .getClass().getClassLoader(), svc.getClass().getInterfaces(), handler);
    return proxy;
  }

  @Override
  public List<LaureateEntity> getLaureates(int startIndex, int fetchSize,
      int sortOrder) {
    BootStrap bs = new BootStrap();
    bs.doBootStrap();

    Context ctx = Context.getCurrentInstance();
    LaureateDao dao = new LaureateDao(ctx.getDaoContext());
    List<LaureateEntity> list = dao.getLaureates(startIndex, fetchSize,
        sortOrder);
    return list;
  }

  @Override
  public List<LaureateEntity> getLaureates(int startIndex, int fetchSize,
      int sortOrder, String category, int yearStart, int yearEnd,
      List<String> countryList) {
    Context ctx = Context.getCurrentInstance();
    LaureateDao dao = new LaureateDao(ctx.getDaoContext());
    List<LaureateEntity> list = dao.getLaureates(startIndex, fetchSize,
        sortOrder, category, yearStart, yearEnd, countryList);
    return list;
  }

  @Override
  public List<String> getCountries() {
    Object o = cacheSvc.get("LaureateCountry", 0L);
    if (o == null)
      return new ArrayList<String>();
    @SuppressWarnings("unchecked")
    List<String> list = (List<String>) o;
    return list;
  }

  private class CountryCacheLoaderCallback implements CacheLoaderCallback {
    @Override
    public List<?> loadList(List<Long> objectIds) {
      return null;
    }

    @Override
    public Object load(Long objectId) {
      Context ctx = Context.getCurrentInstance();
      LaureateDao dao = new LaureateDao(ctx.getDaoContext());
      List<String> list = dao.getCountries();
      return list;
    }
  }

}
